data {
  int<lower=0> n;        // number of obs
  int<lower=0> m;        // number of studies
  int<lower=0> nX;       // number of individual-level parameters
  int<lower=0> nZ;	      // number of study-level parameters
  matrix[n,nX] X;        // predictor matrix indiviual level
  matrix[m,nZ] Z;        // predictor matrix study level
  vector[n] svo;	        // dependent variable
  int<lower=0> study[n]; // study indicator
}
parameters {
  vector[m] beta0;
  vector[m] beta_extro;
  vector[m] beta_open;
  vector[m] beta_agree;
  vector[m] beta_conscien;
  vector[4] mu_beta;
  vector<lower=0>[4] sigma_beta;
  vector[nZ] gamma;
  real<lower=0> sigma_beta0;
  real<lower=0> sigma_svo;
} 
model {
  vector[n] svo_hat;

  for (i in 1:n)
    svo_hat[i] <- beta0[study[i]] + X[i,1] * beta_extro[study[i]] 
      + X[i,2] * beta_open[study[i]] + X[i,3] * beta_agree[study[i]] 
      + X[i,4] * beta_conscien[study[i]];
  beta0 ~ normal(Z * gamma, sigma_beta0);
  svo ~ normal(svo_hat, sigma_svo);
  
  beta_extro ~ normal(mu_beta[1],sigma_beta[1]);
  beta_open ~ normal(mu_beta[2],sigma_beta[2]);
  beta_agree ~ normal(mu_beta[3],sigma_beta[3]);
  beta_conscien ~ normal(mu_beta[4],sigma_beta[4]);
  mu_beta ~ normal(0,1);
  gamma ~ normal(0,1);
  //sigma_beta0 ~ cauchy(0,5);
  //sigma_beta ~ cauchy(0,5);
  //sigma_svo ~ cauchy(0,5);
}

